package com.shanghaionstar.utils;

import android.content.Context;
import android.os.Build;
import android.telephony.TelephonyManager;

import com.onstar.cn.api.OperateB2CService;
import com.onstar.cn.auth.userProfile.Vehicle;
import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.eventservice.ReEventDataElementEntity;
import com.onstar.cn.framework.annotation.http.HeadsValue;
import com.onstar.cn.framework.annotation.http.Request;
import com.onstar.cn.framework.network.entity.RequestEntity;
import com.onstar.cn.framework.network.enumtype.HttpAccept;
import com.onstar.cn.framework.network.enumtype.HttpMethod;
import com.onstar.cn.framework.network.enumtype.Language;
import com.onstar.cn.framework.network.http.ResponseHandler;
import com.onstar.cn.framework.network.http.Sender;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.sqlite.entities.ReEventDataEntity;
import com.onstar.cn.sqlite.entities.RequestEventEntity;
import com.shanghaionstar.enumtype.Event;
import com.shanghaionstar.sqlite.OperateB2cDBService;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * @Title: OperateB2CUtil.java 
 * @Description:事件上传B2CReport
 * @author Xiaofeng Feng
 * @date 2015年8月14日 下午2:15:18 
 */
public class OperateB2CUtil {
	private static final LogManager logger = LogManager.getInstance(); 	// 记录日志
	private static OperateB2cDBService eventService;
	private static ReEventDataEntity data = new ReEventDataEntity();
	private static RequestEventEntity reportList=new RequestEventEntity();
	private static Boolean isCountFull = false;							//本地记录是否满50条
	
	/**
	 * 
	* @Title: operateEvenReportForLogin 
	* @Description: 登陆使用
	* @param @param context    设定文件 
	* @return void    返回类型 
	* @throws
	 */
	public static void operateEvenReportForLogin(Context context){
		reportList.setData(eventService.getList(false));
		SendB2CReport(reportList,context);
	}
	/*
	 * Event事件上送日志to B2CReport
	 * uploadLevel; 	//是立即上传  1立即上传，2满50条上传，3登陆上传
	 */
	public static void operateEventReport(Event event, String transaction, Context context, String uploadLevel) {
		Integer count=0;
		if (context == null)
			return;
		context = context.getApplicationContext();
		/////////////////////////////////////////////////////封装json报文从里向外封装,分三步//////////////////////////////////////////////////
		//第一步：{\"status\":\"success\",\"time\":\"1439538278044\",\"transactionID\":\"F0101\",\"version\":\"5.0.1\"}
		ReEventDataElementEntity content=new ReEventDataElementEntity();
		Vehicle info =ApplicationUtil.getInstance().getCurrentVehicle();
		if(info!=null){
			content.setVin(info.getVin());
		}
		content.setPuserId(ApplicationUtil.getInstance().getIdpID());
		content.setAccount(ApplicationUtil.getInstance().getAccountId());
		// 只有在Event是网络情况且，errorinfo 有值得情况下才会设置为failure，其他情况均为success
		if (event.equals(Event.Connect) && !transaction.equals(Constants.REPORT_SUCCESS)) {
			content.setStatus("failure");
		} else {
			content.setStatus("success");
		}
		content.setTime(System.currentTimeMillis() + "");
		content.setTransactionID(transaction);
		DeviceUtil deviceUtil = new DeviceUtil(context);
		content.setVersion(deviceUtil.getAppVersion());
		String jsonContent = GsonHelper.toJson(content);
		
		//第二步：[{"content":"{\"status\":\"success\",\"time\":\"1439538278044\",\"transactionID\":\"F0101\",\"version\":\"5.0.1\"}","eventID":"1"}]
		data.setContent(jsonContent);
		data.setEventID(event.getStringValue());
		data.setCreateDate(System.currentTimeMillis() + "");
		List<ReEventDataEntity> listdata = new ArrayList<ReEventDataEntity>();
		listdata.add(data);
		
		//第三步：{"accountID":"account","appID":"864895026552842","channelID":"1",
		/*"data":[{"content":"{\"status\":\"success\",\"time\":\"1439538278044\",\"transactionID\":\"F0101\",\"version\":\"5.0.1\"}"
			,"eventID":"1"}],"deviceID":"864895026552842","deviceOS":"5.0.2","deviceToken":"864895026552842","deviceType":"MI 4",
		"eventTS":"1439538324034","language":"zh"}*/
		String deviceId = new DeviceUtil(context).getDeviceID();
		reportList.setAppID(deviceId);
		reportList.setAccountID("account");
		reportList.setChannelID("1");// mobile:1
		reportList.setData(listdata);
		reportList.setDeviceID(deviceId);
		reportList.setDeviceOS(Build.VERSION.RELEASE);
		reportList.setDeviceToken(deviceId);
		reportList.setDeviceType(Build.MODEL);
		reportList.setEventTS(System.currentTimeMillis() + "");
		reportList.setLanguage(Locale.getDefault().getLanguage());
		
		///////////////////////////////////////////////////本地记录满50条上传到B2CReport//////////////////////////////////////////
		try{
			eventService = new OperateB2cDBService(context);
			long addId = eventService.insert(data); 						//将记录保存到本地数据库中
			if(addId >= 1){ 												//添加成功后再查总条数
				if(uploadLevel.equals("1")||uploadLevel.equals("3")){		// 1立即上传，2满50条上传，3登陆上传
					SendB2CReport(reportList,context);
				}else{
					count = eventService.getCount();
					if (count >= 50) { 										//满50条上传
						reportList.setData(eventService.getList(false));	//遍历集合
						SendB2CReport(reportList,context);
						isCountFull=true;
					}
				}
			}
		} catch (Exception e) {
			 AlertDialogUtil.showAlertDialog(context,"", e.getMessage());
		}
	}
	
	// 统一处理发送到服务端B2CReport
	@Request(heads = @HeadsValue(accept = HttpAccept.JSON, language = Language.AUTO), method = HttpMethod.POST)
	public static void SendB2CReport(RequestEventEntity reportList, Context context){
		RequestEntity requestEntity = NetConnectUtil.getAuthRequestEntity(context);
		OperateB2CService service = new OperateB2CService(Constants.CURRENT_SERVER_URL);
		service.eventReport(requestEntity, reportList);
		Sender sender = new Sender();
		sender.send(requestEntity, commandHandler, OperateB2CUtil.class, "SendB2CReport", RequestEventEntity.class, Context.class);
	}
	
	private static ResponseHandler commandHandler = new ResponseHandler() {
		
		@Override
		public void onSuccess(String tag, String json) {
			logger.d(json);
			// 数据上传成功后，删除本地记录的数据
			if(isCountFull){	//本地记录满50条上传到Report
				eventService.deleteAll(null,false);
			}
		}
		
		@Override
		public void onError(String tag, HttpException e) {
			logger.d(e.getMessage());
		}
	};
}
